<template>
  <div class="dict-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="字典名称" prop="dictName">
            <el-input
              v-model="queryParams.dictName"
              placeholder="请输入字典名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="字典类型" prop="dictType">
            <el-input
              v-model="queryParams.dictType"
              placeholder="请输入字典类型"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="字典状态" clearable>
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="multiple" 
        @click="handleDelete"
      >删除</el-button>
      <el-button icon="el-icon-refresh" @click="handleRefreshCache">刷新缓存</el-button>
      <el-button icon="el-icon-upload2" @click="handleImport">导入</el-button>
      <el-button icon="el-icon-download" @click="handleExport">导出</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="dictList"
        @selection-change="handleSelectionChange"
        @row-dblclick="handleRowDblclick"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="字典编号" align="center" prop="id" width="80" />
        <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
        <el-table-column label="字典类型" align="center" prop="dictType" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button 
              type="text" 
              icon="el-icon-view" 
              @click="handleData(scope.row)"
            >数据</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 添加或修改字典类型对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 字典数据对话框 -->
    <el-dialog :title="title" v-model="openData" width="800px" append-to-body>
      <div class="dict-data-header">
        <div class="dict-info">
          <span class="dict-label">字典名称：</span>
          <span class="dict-value">{{ dictData.dictName }}</span>
          <span class="dict-label">字典类型：</span>
          <span class="dict-value">{{ dictData.dictType }}</span>
        </div>
        <div class="dict-actions">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddData">新增</el-button>
          <el-button icon="el-icon-edit" size="small" :disabled="dataFormSingle" @click="handleUpdateData">修改</el-button>
          <el-button 
            type="danger" 
            icon="el-icon-delete" 
            size="small"
            :disabled="dataFormMultiple" 
            @click="handleDeleteData"
          >删除</el-button>
        </div>
      </div>
      <el-table
        v-loading="dataLoading"
        :data="dataList"
        @selection-change="handleDataSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="字典编码" align="center" prop="dictCode" width="80" />
        <el-table-column label="字典标签" align="center" prop="dictLabel" />
        <el-table-column label="字典键值" align="center" prop="dictValue" />
        <el-table-column label="字典排序" align="center" prop="dictSort" width="80" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleDataStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdateData(scope.row)">修改</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDeleteData(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="dataTotal > 0"
        :total="dataTotal"
        v-model:page="dataQueryParams.pageNum"
        v-model:limit="dataQueryParams.pageSize"
        @pagination="getDataList"
      />
    </el-dialog>
    
    <!-- 添加或修改字典数据对话框 -->
    <el-dialog :title="dataTitle" v-model="dataFormOpen" width="600px" append-to-body>
      <el-form ref="dataForm" :model="dataForm" :rules="dataRules" label-width="100px">
        <el-form-item label="字典类型">
          <el-input v-model="dictData.dictType" disabled />
        </el-form-item>
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="字典排序" prop="dictSort">
          <el-input-number v-model="dataForm.dictSort" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelData">取 消</el-button>
          <el-button type="primary" @click="submitDataForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 字典类型相关变量
const loading = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dictList = ref([])
const open = ref(false)
const title = ref('')
const dateRange = ref([])

// 字典数据相关变量
const openData = ref(false)
const dataLoading = ref(false)
const dataIds = ref([])
const dataFormSingle = ref(true)
const dataFormMultiple = ref(true)
const dataTotal = ref(0)
const dataList = ref([])
const dataFormOpen = ref(false)
const dataTitle = ref('')
const dictData = reactive({
  id: undefined,
  dictName: undefined,
  dictType: undefined
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dictName: undefined,
  dictType: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  dictName: undefined,
  dictType: undefined,
  status: 1,
  remark: undefined
})

// 表单校验
const rules = {
  dictName: [
    { required: true, message: '字典名称不能为空', trigger: 'blur' }
  ],
  dictType: [
    { required: true, message: '字典类型不能为空', trigger: 'blur' }
  ]
}

// 字典数据查询参数
const dataQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dictType: undefined
})

// 字典数据表单参数
const dataForm = reactive({
  dictCode: undefined,
  dictLabel: undefined,
  dictValue: undefined,
  dictSort: 0,
  status: 1,
  remark: undefined
})

// 字典数据表单校验
const dataRules = {
  dictLabel: [
    { required: true, message: '字典标签不能为空', trigger: 'blur' }
  ],
  dictValue: [
    { required: true, message: '字典键值不能为空', trigger: 'blur' }
  ],
  dictSort: [
    { required: true, message: '字典排序不能为空', trigger: 'blur' }
  ]
}

// 模拟数据
const mockDictList = [
  {
    id: 1,
    dictName: '用户性别',
    dictType: 'sys_user_sex',
    status: 1,
    remark: '用户性别列表',
    createTime: '2023-01-01 00:00:00'
  },
  {
    id: 2,
    dictName: '菜单状态',
    dictType: 'sys_show_hide',
    status: 1,
    remark: '菜单状态列表',
    createTime: '2023-01-01 00:00:00'
  },
  {
    id: 3,
    dictName: '系统开关',
    dictType: 'sys_normal_disable',
    status: 1,
    remark: '系统开关列表',
    createTime: '2023-01-01 00:00:00'
  },
  {
    id: 4,
    dictName: '任务状态',
    dictType: 'sys_job_status',
    status: 1,
    remark: '任务状态列表',
    createTime: '2023-01-01 00:00:00'
  },
  {
    id: 5,
    dictName: '系统是否',
    dictType: 'sys_yes_no',
    status: 1,
    remark: '系统是否列表',
    createTime: '2023-01-01 00:00:00'
  }
]

// 模拟字典数据
const mockDictDataList = {
  'sys_user_sex': [
    {
      dictCode: 1,
      dictLabel: '男',
      dictValue: '0',
      dictSort: 1,
      status: 1,
      remark: '性别男'
    },
    {
      dictCode: 2,
      dictLabel: '女',
      dictValue: '1',
      dictSort: 2,
      status: 1,
      remark: '性别女'
    },
    {
      dictCode: 3,
      dictLabel: '未知',
      dictValue: '2',
      dictSort: 3,
      status: 1,
      remark: '性别未知'
    }
  ],
  'sys_normal_disable': [
    {
      dictCode: 1,
      dictLabel: '正常',
      dictValue: '0',
      dictSort: 1,
      status: 1,
      remark: '正常状态'
    },
    {
      dictCode: 2,
      dictLabel: '停用',
      dictValue: '1',
      dictSort: 2,
      status: 1,
      remark: '停用状态'
    }
  ]
}

// 查询字典类型列表
const getList = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    dictList.value = mockDictList
    total.value = mockDictList.length
    loading.value = false
  }, 500)
}

// 查询字典数据列表
const getDataList = () => {
  if (!dictData.dictType) {
    return
  }
  dataLoading.value = true
  // 模拟接口请求
  setTimeout(() => {
    const dictDataItems = mockDictDataList[dictData.dictType] || []
    dataList.value = dictDataItems
    dataTotal.value = dictDataItems.length
    dataLoading.value = false
  }, 500)
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.dictName = undefined
  form.dictType = undefined
  form.status = 1
  form.remark = undefined
}

// 字典数据表单重置
const resetDataForm = () => {
  dataForm.dictCode = undefined
  dataForm.dictLabel = undefined
  dataForm.dictValue = undefined
  dataForm.dictSort = 0
  dataForm.status = 1
  dataForm.remark = undefined
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.dictName = undefined
  queryParams.dictType = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 字典数据多选框选中数据
const handleDataSelectionChange = (selection) => {
  dataIds.value = selection.map(item => item.dictCode)
  dataFormSingle.value = selection.length !== 1
  dataFormMultiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加字典类型'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const dictId = row?.id || ids.value[0]
  // 模拟获取字典类型详情
  const dictInfo = mockDictList.find(item => item.id === dictId)
  if (dictInfo) {
    Object.assign(form, dictInfo)
  }
  open.value = true
  title.value = '修改字典类型'
}

// 提交按钮
const submitForm = () => {
  // 模拟提交
  ElMessage.success(form.id ? '修改成功' : '新增成功')
  open.value = false
  getList()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 删除按钮操作
const handleDelete = (row) => {
  const dictIds = row?.id ? [row.id] : ids.value
  
  ElMessageBox.confirm('确认删除已选中的字典类型?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 字典状态修改
const handleStatusChange = (row) => {
  const text = row.status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确认要${text}该字典类型吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟修改状态
    ElMessage.success(`${text}成功`)
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1
  })
}

// 字典数据状态修改
const handleDataStatusChange = (row) => {
  const text = row.status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确认要${text}该字典数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟修改状态
    ElMessage.success(`${text}成功`)
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1
  })
}

// 刷新缓存按钮操作
const handleRefreshCache = () => {
  ElMessageBox.confirm('确认要刷新字典缓存吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟刷新缓存
    ElMessage.success('刷新缓存成功')
  }).catch(() => {})
}

// 导入按钮操作
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 双击行查看字典数据
const handleRowDblclick = (row) => {
  handleData(row)
}

// 查看字典数据按钮操作
const handleData = (row) => {
  Object.assign(dictData, row)
  dataQueryParams.dictType = row.dictType
  openData.value = true
  title.value = '字典数据'
  getDataList()
}

// 新增字典数据按钮操作
const handleAddData = () => {
  resetDataForm()
  dataFormOpen.value = true
  dataTitle.value = '添加字典数据'
}

// 修改字典数据按钮操作
const handleUpdateData = (row) => {
  resetDataForm()
  const dictCode = row?.dictCode || dataIds.value[0]
  // 模拟获取字典数据详情
  const dictDataItems = mockDictDataList[dictData.dictType] || []
  const dictDataInfo = dictDataItems.find(item => item.dictCode === dictCode)
  if (dictDataInfo) {
    Object.assign(dataForm, dictDataInfo)
  }
  dataFormOpen.value = true
  dataTitle.value = '修改字典数据'
}

// 提交字典数据表单
const submitDataForm = () => {
  // 模拟提交
  ElMessage.success(dataForm.dictCode ? '修改成功' : '新增成功')
  dataFormOpen.value = false
  getDataList()
}

// 取消字典数据表单
const cancelData = () => {
  dataFormOpen.value = false
  resetDataForm()
}

// 删除字典数据按钮操作
const handleDeleteData = (row) => {
  const dictCodes = row?.dictCode ? [row.dictCode] : dataIds.value
  
  ElMessageBox.confirm('确认删除已选中的字典数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getDataList()
  }).catch(() => {})
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.dict-container {
  padding: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.dict-data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.dict-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.dict-label {
  font-weight: bold;
  margin-right: 5px;
  color: #606266;
}

.dict-value {
  margin-right: 20px;
  color: #333;
}
</style> 